#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/11 11:12
# @Author  : jeff
# @FileName: base_model
from flask_sqlalchemy import SQLAlchemy

# Create a global db object
db = SQLAlchemy()


# base model
class BaseModel(db.Model):
    __abstract__ = True

    @classmethod
    def insert(cls, data):
        """
        Insert into database instance
        :return:
        """
        db.session.add(data)

    @classmethod
    def delete(cls, id):
        """
        Delete database instance
        :return:
        """
        cls.query.filter_by(id=id).delete()
        try:
            db.session.commit()
            return True
        except Exception:
            db.session.rollback()
            raise

    @classmethod
    def query_all(cls):
        """
        Query all database instances
        :return:
        """
        return cls.query.all()

    @classmethod
    def query_by_id(cls, id):
        """
        Query database instance based on id
        :param id:
        :return:
        """
        return cls.query.filter_by(id=id).first()

    def update(self, **kwargs):
        """
        Update database instance
        :param kwargs:
        :return:
        """
        for key, value in kwargs.items():
            setattr(self, key, value)
        try:
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            return str(e)

    @classmethod
    def query_by_page(cls, page, per_page):
        """
        Paging query
        :param page:
        :param per_page:
        :return:
        """
        return cls.query.paginate(page, per_page, False)

    def format_created_time(self):
        """
        Format time
        :return:
        """
        return self.created_time.strftime('%Y-%m-%d %H:%M:%S')